package com.iaiai.cobra.core;

import com.iaiai.cobra.common.constant.ResultCode;
import com.iaiai.cobra.common.util.JsonUtil;
import com.iaiai.cobra.common.vo.ResultVo;
import com.iaiai.cobra.core.config.ProjectConfig;
import com.iaiai.cobra.web.vo.OnlineVo;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;

/**
 * Created with BaseController.
 * Package: com.iaiai.cobra.core.db
 * Author: iaiai
 * Create Time: 2024/6/22 18:01
 * QQ: 176291935
 * Email: 176291935@qq.com
 * Description:
 */
public class BaseController {

    @Autowired
    protected ServiceManager serviceManager;

    @Autowired
    protected ProjectConfig projectConfig;

    @Autowired
    protected HttpServletRequest request;

    protected ResultVo success(){
        ResultVo resultVo = new ResultVo();
        resultVo.setCode(ResultCode.SUCCESS.getValue());
        return resultVo;
    }

    protected <T> ResultVo<T> success(T result){
        ResultVo<T> resultVo = new ResultVo<T>();
        resultVo.setCode(ResultCode.SUCCESS.getValue());
        resultVo.setResult(result);
        return resultVo;
    }

    protected ResultVo fail(String msg){
        ResultVo resultVo = new ResultVo();
        resultVo.setCode(ResultCode.FAIL.getValue());
        resultVo.setMsg(msg);
        return resultVo;
    }

    //返回当前token
    protected String getToken(){
        return request.getHeader("token");
    }

    //获取登录用户
    protected OnlineVo getOnline() throws IOException {
        String json = serviceManager.redisAdminCache.getLogin(getToken());
        if(StringUtils.isEmpty(json))return null;

        return JsonUtil.getInstance().deserialize(json, OnlineVo.class);
    }

}
